package service;
import mapper.BrandMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import pagination.PageBean;
import pojo.Brand;
import utils.SqlSessionFactoryUtils;

//业务层

import java.util.List;
public class BrandService {
    public List<Brand> selectAll(){
        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = factory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brandList = mapper.selectAll();
        sqlSession.close();
        return brandList;
    }

    public void add(Brand brand){
        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = factory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.add(brand);
        sqlSession.commit();
        sqlSession.close();
    }

    public Brand selectById(int id){
        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = factory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        Brand brand = mapper.selectById(id);
        sqlSession.close();
        return brand;
    }

    public void update(Brand brand){
        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = factory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.update(brand);
        sqlSession.commit();
        sqlSession.close();
    }

    public void delete(int id){
        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = factory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.deleteById(id);
        sqlSession.commit();
        sqlSession.close();
    }
    public PageBean<Brand> selectAllPage(int currentPage, int pageSize){
        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = factory.openSession();

        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        int beginIndex = (currentPage -1 ) * pageSize;
        List<Brand> brandList = brandMapper.selectAllPage(beginIndex ,pageSize);
        int totalCount = brandMapper.selectCount();

        PageBean<Brand> pageBean = new PageBean<>();
        pageBean.setData(brandList);
        pageBean.setCurrentPage(currentPage);
        pageBean.setPageSize(pageSize);
        pageBean.setTotalCount(totalCount);

        int totalPage = (int) Math.ceil( totalCount*1.0/pageSize );
        pageBean.setTotalPage(totalPage);

        sqlSession.close();
        return pageBean;

    }
}

